package com.situation.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.situation.mapper.LoginLogMapper;
import com.situation.pojo.DO.TbLoginLog;
import com.situation.pojo.VO.UserVO;
import com.situation.service.LoginLogService;
import com.situation.util.AddressUtil;
import com.situation.util.IPUtil;
import eu.bitwalker.useragentutils.Browser;
import eu.bitwalker.useragentutils.OperatingSystem;
import eu.bitwalker.useragentutils.UserAgent;
import nonapi.io.github.classgraph.utils.VersionFinder;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.lang.model.element.VariableElement;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class LoginLogServiceImpl implements LoginLogService {

    @Autowired
    private LoginLogMapper loginLogMapper;

    /**
     * 添加登入日志
     *
     * @param request
     * @return
     */
    @Override
    @Transactional
    public int add(HttpServletRequest request) {
        String username = (String) SecurityUtils.getSubject().getPrincipal();
        TbLoginLog loginLog = new TbLoginLog();
        loginLog.setUsername(username);
        loginLog.setIp(IPUtil.getIpAddr(request));
        loginLog.setLocation(AddressUtil.getCityInfo(IPUtil.getIpAddr(request)));
        // 获取客户端操作系统
        UserAgent userAgent = UserAgent.parseUserAgentString(request.getHeader("User-Agent"));
        Browser browser = userAgent.getBrowser();
        OperatingSystem os = userAgent.getOperatingSystem();
        loginLog.setUserSystem(os.getName());
        loginLog.setUserBrowser(browser.getName());
        loginLog.setLoginTime(LocalDateTime.now());
        return loginLogMapper.add(loginLog);
    }

    /**
     * 删除
     *
     * @param id
     * @return
     */
    @Override
    public int delete(Long id) {
        return loginLogMapper.delete(id);
    }

    /**
     * 批量删除
     *
     * @param longList
     * @return
     */
    @Override
    @Transactional
    public int batchDelete(List<Long> longList) {
        return loginLogMapper.batchDelete(longList);
    }

    /**
     * 查询
     *
     * @return
     */
    @Override
    public PageInfo<TbLoginLog> findAll(int pageNum, int pageSize, TbLoginLog loginLog) {
        PageHelper.startPage(pageNum, pageSize);
        return new PageInfo<>(loginLogMapper.findAll(loginLog));
    }

    /**
     * 登陆报表
     * @param userVO
     * @return
     */
    @Override
    public List<Map<String, Object>> loginReport(UserVO userVO) {
        return loginLogMapper.userLoginReport(userVO);
    }
}
